package com.longg.filter;

import com.longg.service.IUserService;
import com.longg.service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebFilter("/index.jsp")
public class RememberFilter implements Filter {
    private IUserService service = new UserServiceImpl();
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)servletRequest;
        HttpServletResponse resp = (HttpServletResponse)servletResponse;

        Cookie[] cookies = req.getCookies();
        if(cookies != null){
            for(Cookie cookie : cookies){
                if ("uName".equals(cookie.getName())){
                    Map<String,Object> userInfoMap = service.getUserBaseInfo(cookie.getValue());
                    req.getSession().setAttribute("userInfoMap",userInfoMap);
                    resp.sendRedirect(req.getContextPath() + "/assets/html/home.jsp");
                    return;
                }
            }
        }
        filterChain.doFilter(req,resp);
    }

    @Override
    public void destroy() {

    }
}
